package net.zjitc.controller;

import jakarta.servlet.http.HttpServletRequest;
import net.zjitc.pojo.Admin;
import net.zjitc.service.AdminService;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import net.zjitc.utils.MD5Utils;
import net.zjitc.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;


@RestController
@RequestMapping("/admin")
//@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("admin")
    public APIResponse<Admin> getAdmin() {
        String token = request.getHeader("token");
        return APIResponse.suc("获取成功", adminService.getAdmin(token));
    }
    @PostMapping("/login")
    public APIResponse<Token> login(@RequestBody Admin admin) throws NoSuchAlgorithmException {
        Admin loginAdmin = adminService.login(admin);
        if(loginAdmin == null){
            return APIResponse.err("用户名或密码错误",null);
        }
//        如果验证成功，生成JWT令牌并封装到Token对象中，返回成功响应，提示“登录成功”。
        return APIResponse.suc("登录成功", new Token(new JwtUtil().generateToken(loginAdmin.getUsername())));
    }
    @PostMapping("admin/changePassword")
    public APIResponse<Admin> update(@RequestBody Admin admin) throws NoSuchAlgorithmException {
        Admin updateAdmin = getAdmin().getData();
        System.out.println(updateAdmin);
        updateAdmin.setPassword(admin.getPassword());
        Integer result = adminService.updateAdmin(updateAdmin);
        if(result == 0){
            return APIResponse.err("修改失败",null);
        }
        return APIResponse.suc("修改成功",null);
    }

    @PostMapping(value = "admin/changeAvatar")
    public APIResponse<Admin> avatar(@RequestBody Admin admin) throws NoSuchAlgorithmException {
        Admin updateAdmin = getAdmin().getData();
        updateAdmin.setAvatar(admin.getAvatar());
        Integer result = adminService.updateAvatar(updateAdmin);
        if(result == 0){
            return APIResponse.err("修改失败",null);
        }
        return APIResponse.suc("修改成功",null);
    }

}
